package com.zhangxu.microservice.system.web.config.mvc;

import com.zhangxu.microservice.system.web.config.interceptor.AeLoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * MVC配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    private AeLoginInterceptor aeLoginInterceptor;

    /**
     * 配置路径匹配
     * 为所有RestController添加/api/system前缀
     */
    @Override
    public void configurePathMatch(@NonNull PathMatchConfigurer configurer) {
        configurer.addPathPrefix("/api/system", c -> {
            String packageName = Optional.ofNullable(c.getPackage()).map(Package::getName).orElse("");
            return packageName.startsWith("com.zhangxu.microservice.system.web.controller")
                    && c.isAnnotationPresent(RestController.class);
        });
    }

    /**
     * 添加拦截器
     * 拦截/api/system/ae/**路径下的所有请求
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //全部拦截
        String aePathPatterns = "/api/system/ae/**";
        registry.addInterceptor(aeLoginInterceptor).addPathPatterns(aePathPatterns);
    }
}